package com.hwxt.ghs.service;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.exc.StreamWriteException;
import com.fasterxml.jackson.databind.DatabindException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hwxt.ghs.vo.Project;

/**
 * 项目服务
*/
@Service
public class ProjectService {

    @Value("${lucene_directory}")
    private String lucene_directory;
    
    @Autowired
    private ObjectMapper mapper;	

    
    public List<Project> getProjectList() {
        List<Project> result =new ArrayList<>();
        File jsonFile = new File(lucene_directory, "projects.json");
        if(jsonFile.exists() && jsonFile.length() > 0) {
            try {
                result = mapper.readValue(new FileReader(jsonFile), mapper.getTypeFactory().constructCollectionType(List.class, Project.class));
            } catch (Exception e) {
                System.err.println("读取项目列表失败");
                e.printStackTrace();
            }
        } else {
            System.err.println("项目列表文件不存在");
        }
        return result;
    }


    public List<Project> addProject(Project project) {
        List<Project> result =  getProjectList();
        result.add(project);
        saveProjects(result);
        return result;
    }
    public void saveProjects(List<Project> projects){
        File jsonFile = new File(lucene_directory, "projects.json");
        try {
            mapper.writeValue(jsonFile, projects);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void deleteProject(String path) {
        List<Project> result =  getProjectList();
        for(Project project : result) {
            if(project.getIndexpath().equals(path)) {
                result.remove(project);
                break;
            }
        }
        saveProjects(result);
    }

    
}
